using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
public class GameManager : MonoBehaviour {
	private enum GameState{
		Init = 0,
		Initing = 1,
		Game = 2,
	}
	private GameState gameState = GameState.Init;
	private Dictionary<ManagerType,BaseManager> mManagerList = new Dictionary<ManagerType, BaseManager>();
	private Dictionary<string,BasePanel> mPanelList = new Dictionary<string, BasePanel>();
	private BasePanel curPanel;
	private static GameManager mInstance;
	private GameObject mPanelBase;
	public static GameManager GetInstatnce(){
		return mInstance;
	}
	// Use this for initialization
	void Start () {
		mInstance = this;
		mPanelBase = GameObject.Find("PanelBase");
	}
	
	// Update is called once per frame
	void Update () {
		switch(gameState){
		case GameState.Init:
			StartCoroutine(Init());
			break;
		case GameState.Initing:
			break;
		}
	}
	public IEnumerator Init(){
		gameState = GameState.Initing;
		yield return StartCoroutine(InitAllPool());
		RegistAllManager();
		gameState = GameState.Game;
		ShowPanel(PanelName.MainMenuPanel);
	}
	#region manager
	public void RegistAllManager(){
		HeroManager tHeroManager = new HeroManager();
		tHeroManager.Init();
		mManagerList.Add(ManagerType.HERO,tHeroManager);
		MissonManager tMissonManager = new MissonManager();
		tMissonManager.Init();
		mManagerList.Add(ManagerType.MISSION,tMissonManager);
	}
	public BaseManager GetManager(ManagerType type){
		if(mManagerList.ContainsKey(type)){
			return mManagerList[type];
		}else{
			throw new Exception("Not Find Manager,type = "+ type);
		}
	}
	#endregion
	public IEnumerator InitAllPool(){
		HeroPool heroPool = new HeroPool();
		yield return StartCoroutine(heroPool.Init());
		MissonPool missonPool = new MissonPool();
		yield return StartCoroutine(missonPool.Init());
	}
	#region Panel 
	public void ShowPanel(string name){
		HidePanel(curPanel);
		StartCoroutine(ShowPanelCoroutine(name));
	}
	private void HidePanel(BasePanel panel){
		if(panel != null){
			NGUITools.SetActive(panel.gameObject,false);
		}
	}
	private IEnumerator ShowPanelCoroutine(string name){
		
		BasePanel panel = null;
		if(mPanelList.ContainsKey(name)){
			
			panel = mPanelList[name];
			mPanelList.Add(name,panel);
		}else{
			ResGameObject obj = new ResGameObject();
			yield return StartCoroutine(ResManager.GetInstance().Load("Prefabs/Panel/" + name,obj));
			GameObject gameObj = NGUITools.AddChild(mPanelBase,obj.obj as GameObject);
			
			panel = gameObj.GetComponent<BasePanel>();
			yield return StartCoroutine(panel.Init());
		}
		curPanel = panel;
		NGUITools.SetActive(curPanel.gameObject,true);
		curPanel.Refresh();
	}
	public BasePanel GetCurPanel(){
		return curPanel;
	}
	public void RefreshCurPanel(){
		if(curPanel != null){
			curPanel.Refresh();
		}
	}
	#endregion
}
